<template>
	<view class="content">
		<scroll-view :scroll-y="true" :style="{'height':windowHeight+'px'}">
			<block v-for="(item,index) in conversations" :key="index">
				<uni-swipe-action>
					<uni-swipe-action-item :right-options="options" @click="delHandle(item.id)">
						<view class="good-item">
							<view class="good-info">
								<view style="display: flex;">
									<view style="position: relative;">
										<view class="nav-counter" v-if="item.unread>0">{{item.unread}}</view>
										<image class="info-left" :src="item.data.avatar" @click="goToFriendInfo(item)">
										</image>
									</view>
									<view class="info-right" @click="goToUrl(item)">
										<view class="name">{{item.data.nickname}}</view>
										<view class="price" v-if="item.lastMessage.type=='text'">
											{{handleMessage(item.lastMessage.payload.text)}}
										</view>
										<view class="price" v-else-if="item.lastMessage.type=='image'">[图片]</view>
										<view class="price" v-else-if="item.lastMessage.type=='audio'">[语音]</view>
										<view class="price" v-else>[文件]</view>
										<u-line style="margin-top: 20rpx;" />
									</view>
								</view>
								<view class="time-info">{{item.lastMessage.timestamp | weChatTimeFormat}}</view>
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</block>
		</scroll-view>
	</view>
</template>

<script>
	import GoEasy from 'goeasy';
	import {
		imMessage
	} from '../../api/ai.js';
	import {
		getConversations,
		getMessageList,
		getUserInfo,
		isNeedAIMessage
	} from '../../api/login.js';
	import weChatTimeFormat from "../../utils/time.js"
	export default {
		data() {
			return {
				windowHeight: 0, //可视区域的高度
				unreadTotal: 0, //未读消息总数
				conversations: [],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}]
			};
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight;
				}
			});
			if (!uni.getStorageSync('userId')) {
				uni.showModal({
					'title': "提示",
					content: '请先登录',
					success:function(res){
						if (res.confirm) {
							uni.switchTab({
								url: '/pages/userHome/userHome'
							})
						}
					}
				})
			}
			getUserInfo({
				id: uni.getStorageSync("userId")
			}).then(res => {
				this.connectionGoEasy(res.data.uuid, res.data.avatar, res.data.username)
			}).catch(err => {
				console.log(err)
			})
			this.aiSendMessage()

			setTimeout(() => {
				this.getMessageList()
				//监听会话列表变化 并返回最新的会话列表
				let that = this;
				let onConversationsUpdated = function(content) {
					that.unreadTotal = content.unreadTotal
					that.conversations = content.conversations
				};
				//监听会话列表更新
				this.goEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated);
			}, 600)
		},
		onUnload() {
			let that = this;
			let onConversationsUpdated = function(content) {
				that.unreadTotal = content.unreadTotal
				that.conversations = content.conversations
			};
			this.goEasy.im.off(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated);
		},
		
		onPullDownRefresh() {
			this.getMessageList()
		},
		onShow() {
		},

		methods: {
			delHandle(id) {
				this.conversations = this.conversations.filter(item => item.id !== id);
			},
			handleMessage(text) {
				if (text.length > 20) {
					return text.slice(0, 20) + '...'
				}
				return text
			},
			goToUrl(item) {
				uni.navigateTo({
					url: '/pages_subpackage/messageControl/test?item=' + encodeURIComponent(JSON.stringify(item))
				});
			},
			goToFriendInfo(item) {
				uni.navigateTo({
					url: '/pages_subpackage/friendInfo/index?item=' + encodeURIComponent(JSON.stringify(item))
				});
			},
			//获取最新的会话列表
			getMessageList() {
				let that = this
				var im = this.goEasy.im;
				im.latestConversations({
					onSuccess: function(result) {
						that.unreadTotal = result.content.unreadTotal
						that.conversations = result.content.conversations
						if (that.conversations.length == 0) {
							that.getMessageListByGo()
						}
					},
					onFailed: function(error) { //获取失败
						console.log("Failed to get the latest conversations, code:" + error.code +
							" content:" + error.content);
					},
				});
				uni.stopPullDownRefresh()
			},
			getMessageListByGo() {
				getConversations({
					uuid: uni.getStorageSync("uuid")
				}).then(res => {
					this.conversations = res.data
				}).catch(err => {
					this.conversations = []
				})
			},
			connectionGoEasy(uuid, avatar, nickname) {
				if (this.goEasy.getConnectionStatus() === "disconnected") {
					//建立连接
					this.goEasy.connect({
						id: uuid, //im必填，最大长度60字符
						data: {
							"avatar": avatar,
							"nickname": nickname
						}, //必须是一个对象，im必填，最大长度300字符，显示在会话列表中
						onSuccess: function() { //连接成功
							console.log("GoEasy connect successfully.") //连接成功
						},
						onFailed: function(error) { //连接失败
							console.log("Failed to connect GoEasy, code:" + error.code + ",error:" + error
								.content);
						},
						onProgress: function(attempts) { //连接或自动重连中
							console.log("GoEasy is connecting", attempts);
						}
					});
				}
			},
			aiSendMessage() {
				let currentUser = uni.getStorageSync("userInfo")
				console.log("这是当前登录的用户", currentUser)
				isNeedAIMessage({
					uuid: uni.getStorageSync("uuid")
				}).then(res => {
					//AI首次发送消息
					let imParams = {
						appkey: "BC-85c4b28d6f1e4126a13a804f4e9a34a3",
						senderId: res.data.uuid,
						senderData: {
							"avatar": res.data.avatar,
							"nickname": res.data.username
						},
						to: {
							"type": "private",
							"id": uni.getStorageSync("uuid"),
							"data": {
								"avatar": currentUser.avatar,
								"nickname": currentUser.username
							}
						},
						type: "text",
						payload: "你好呀，我是你的情感导师",
					}
					imMessage(imParams).then(res => {
						console.log("im发送消息成功", res)
					}).catch(err => {
						console.log("发送消息失败", err)
					})
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
	.good-item {
		position: relative;
		width: 100%;
		background: #fff;
		display: flex;

		// margin-bottom: 30rpx;
		.good-info {
			display: flex;
			padding: 20rpx;
			font-size: 28rpx;
			justify-content: space-around;
			width: 100%;

			.info-left {
				width: 120rpx;
				height: 120rpx;
				margin-right: 16rpx;
			}

			.info-right {
				width: 420rpx;

				.name {
					font-size: 40rpx;
				}

				.price {
					padding: 10rpx 0;
					font-size: 32rpx;
				}
			}

			.time-info {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				color: #909399;
			}

		}

		.del-btn {
			position: absolute;
			top: 0;
			right: -140rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 20;
			width: 140rpx;
			height: 100%;
			background: #007AFF;
			color: #fff;
		}
	}

	.nav-counter {
		position: absolute;
		top: 0px;
		right: 0px;
		min-width: 8px;
		height: 20px;
		line-height: 20px;
		margin-top: -11px;
		padding: 0 6px;
		font-weight: normal;
		color: white;
		text-align: center;
		text-shadow: 0 1px rgba(0, 0, 0, 0.2);
		background: #e23442;
		// border: 1px solid #911f28;
		border-radius: 11px;
		background-image: -webkit-linear-gradient(top, #e8616c, #dd202f);
		background-image: -moz-linear-gradient(top, #e8616c, #dd202f);
		background-image: -o-linear-gradient(top, #e8616c, #dd202f);
		background-image: linear-gradient(to bottom, #e8616c, #dd202f);
		-webkit-box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.1), 0 1px rgba(0, 0, 0, 0.12);
		box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.1), 0 1px rgba(0, 0, 0, 0.12);
	}


	page {
		background: #f4f4f4;
	}
</style>